<script setup lang="ts">
import { computed } from 'vue'
import type { PropType } from 'vue'

// Define types for better type safety
type TagType = 'success' | 'warning' | 'info' | 'primary' | 'danger' | undefined

interface TagOption {
  value: string | number
  label?: string
  type?: TagType
  bgColor?: string
  textColor?: string
}

interface TagItem {
  label: string | number
  type?: TagType
  bgColor?: string
  textColor?: string
}

interface Scope {
  row: Record<string, unknown>
}

interface ItemProp {
  prop: string
  options: TagOption[]
}

const props = defineProps({
  scope: {
    type: Object as PropType<Scope>,
    required: true,
    default: () => ({ row: {} }),
  },
  item: {
    type: Object as PropType<ItemProp>,
    required: true,
    default: () => ({ prop: '', options: [] }),
  },
})

const items = computed<TagItem[]>(() => {
  const { row } = props.scope
  const { prop, options } = props.item

  // Convert options array to object for faster lookup
  const optionsMap = options.reduce<Record<string | number, TagOption>>((acc, option) => {
    acc[option.value] = option
    return acc
  }, {})

  const propValue = row[prop]

  // Handle array values
  if (Array.isArray(propValue)) {
    return propValue.map((value) => ({
      label: optionsMap[value]?.label ?? value,
      type: optionsMap[value]?.type,
      bgColor: optionsMap[value]?.bgColor,
      textColor: optionsMap[value]?.textColor,
    }))
  }

  // Handle primitive values (string/number)
  if (typeof propValue === 'string' || typeof propValue === 'number') {
    const option = optionsMap[propValue]
    return [
      {
        label: option?.label ?? propValue,
        type: option?.type,
        bgColor: option?.bgColor,
        textColor: option?.textColor,
      },
    ]
  }

  // Fallback for other types (objects, etc.)
  return [
    {
      label: JSON.stringify(propValue),
    },
  ]
})
</script>

<template>
  <el-tag
    v-for="(item, index) in items"
    :key="index"
    :type="item.type"
    :color="item.bgColor"
    :style="{ color: item.textColor }"
    effect="light"
  >
    {{ item.label }}
  </el-tag>
</template>
